require 'cairo'

function conky_draw_cava()
    if conky_window == nil then
        return
    end

    local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, conky_window.width, conky_window.height)
    cr = cairo_create(cs)

    local bars = 16 -- 频谱条数
    local bar_width = 5 -- 每个条的宽度
    local bar_spacing = 2 -- 条之间的间距
    local max_height = 100 -- 最大高度

    -- 读取 Cava 输出
    local file = io.open("/tmp/cava_fifo", "r")
    if not file then
        return
    end
    local data = file:read("*line")
    file:close()

    -- 解析数据
    local values = {}
    for value in string.gmatch(data, "%d+") do
        table.insert(values, tonumber(value))
    end

    -- 绘制频谱
    local x = 10
    for i = 1, bars do
        local height = values[i] / 128 * max_height
        cairo_set_source_rgba(cr, 1, 0, 0, 1) -- 设置颜色为红色
        cairo_rectangle(cr, x, max_height - height, bar_width, height)
        cairo_fill(cr)
        x = x + bar_width + bar_spacing
    end

    cairo_destroy(cr)
    cairo_surface_destroy(cs)
end
